package com.example.demo.controller;

import com.example.demo.controller.requests.AddDrinkRequest;
import com.example.demo.controller.requests.ModifyDrinkRequest;
import com.example.demo.model.Drink;
import com.example.demo.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
//@Controller
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    public IDrinkService drinkService;

    //    返回所有饮品的接口
    // get /drink/
//    @RequestMapping(value = "/",method = RequestMethod.GET)
    @GetMapping("/")
//    @ResponseBody
    public List<Drink> getAll(Integer page, Integer limit) {//返回值是json数组
//        后期从数据库查询
//        前端传来的参数封装成pageRequest
//        分页查询
        PageRequest pageRequest = PageRequest.of(page-1, limit);

        List<Drink> all= drinkService.getAllDrinks(pageRequest).getContent();
        return all;
    }

    //    查询某个指定的饮品
//    get /dink/1
//    get /drink/？id=1
    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable("id") Integer id) {//类和方法的修饰写在前面
        log.info("要查询的饮品id：{}", id);
        Drink drink = Drink.builder().id(1)
                .name("四季春奶茶")
                .price(Money.parse("USD 12.00"))
                .build();
        return drink;
    }

    //   新增
//    post /drink/ {"name":"奶茶","price":"8.0"}
//    传参思路
//    直接使用实体类 Valid数据校验
    @PostMapping("/")
    public Drink addNewDrink(@RequestBody @Valid AddDrinkRequest request,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;//给前端返回空值
        } else {
//            新增饮品
            log.info("新增饮品：{}", request);
            Drink saveDrink = new Drink();
            BeanUtils.copyProperties(request,saveDrink);
            drinkService.addNewDrink(saveDrink, request.getCategoryId());
            return saveDrink;
        }
    }

    //    修改饮品 update
//    put /drink/ {"id" : "1","name=  ","price= "}
    @PutMapping("/")
    public Drink modifyDrink(@RequestBody ModifyDrinkRequest request) {
        log.info("要修改的饮品：{}", request);
//        1.查看有无饮品
        Drink drink = drinkService.getDrinkById(request.getId());
//        2.把要修改的内容=》drink对应属性
        BeanUtils.copyProperties(request,drink);
//        3.更新数据库
        drinkService.updateDrink(drink);
        return drink;
    }

    //    删除饮品
//    delete /drink/1
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id) {
        log.info("要删除的饮品id：{}", id);
        drinkService.deleteDrink(id);
        return "删除操作成功";
    }

    //    文件上传
//        file.getInputStream();
//        split()
    @PostMapping( value="/batch",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public List<Drink> uploadFile(MultipartFile file) {
        List<Drink> results=new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = "";
            while ((line=reader.readLine()) != null) {
//            解析每一行 "1 , name , price"
                String[] args = line.split(",");
                results.add(Drink.builder().id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"), Double.parseDouble(args[2])))
                        .build());
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return results;
    }
//        String line=reader.readLine();
//        InputStream inputStream=file.getInputStream();
//        InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
//        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);


//        String path="D:/javaWed/File";
//        String filePath=path + file.getOriginalFilename();
//        File saveFile=new File(filePath);
//        StringBuffer buffer=new StringBuffer();
//        for (MultipartFile multipartFile : file ) {
//            String str = uploadFile(multipartFile);
//            buffer.append(str);
//            buffer.append(",");
//        }
//
//        try {
//            file.transferTo(saveFile);
//        }catch (IOException e){
//            e.printStackTrace();
//            return "上传失败";
//        }
//        return "上传成功";
}
